package leetcode.primary;

import utils.linkedList.ListNode;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class T19 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode p = head;
        ListNode q = head;
        int count = 0;
        int flag = 0;
        while(p.next!=null){
            p = p.next;
            count++;
            if(flag==1){
                q=q.next;
            }
            if(count==n){
                flag=1;
            }
        }
        if(flag==1){
            q.next = q.next.next;
        }else{
            head = head.next;
        }
        return head;
    }
}